package com.lonely.system.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lonely.common.core.domain.auth.LoginUser;
import com.lonely.common.utils.JsonUtil;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.framework.web.service.TokenService;
import com.lonely.system.domain.entity.SysUserRole;
import com.lonely.system.service.ISysDataPermissionsService;
import com.lonely.system.service.ISysRoleMenuService;
import com.lonely.system.service.ISysUserRoleService;
import com.lonely.system.service.ISysUserService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 黄志标
 * @date: 2025/6/10 10:49
 * @description:
 */
public class AuthUtil {

    private static final ISysUserRoleService SYS_USER_ROLE_SERVICE = SpringUtil.getBean(ISysUserRoleService.class);

    private static final ISysRoleMenuService SYS_ROLE_MENU_SERVICE = SpringUtil.getBean(ISysRoleMenuService.class);

    private static final ISysUserService SYS_USER_SERVICE = SpringUtil.getBean(ISysUserService.class);

    private static final ISysDataPermissionsService SYS_DATA_PERMISSIONS_SERVICE = SpringUtil.getBean(ISysDataPermissionsService.class);

    private static final TokenService TOKEN_SERVICE = SpringUtil.getBean(TokenService.class);

    /**
     * 重新刷新用户权限
     *
     * @param userId
     */
    public static void refreshUserPermission(Long userId) {
        // 判断当前操作用户是否是登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.equals(loginUser.getUser().getUserId(), userId)) {
            // 重新查询权限信息
            if (!loginUser.getUser().isAdmin()) {
                // 获取用户关联的角色信息
                List<Long> roleIds = Optional.ofNullable(SYS_USER_ROLE_SERVICE.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId))).orElse(new ArrayList<>())
                        .stream().map(SysUserRole::getRoleId).distinct().collect(Collectors.toList());
                loginUser.setPermissions(new HashSet<>(SYS_ROLE_MENU_SERVICE.batchGetMenuPermsByRoleId(roleIds)));
                loginUser.setUser(SYS_USER_SERVICE.selectUserByUserId(loginUser.getUser().getUserId()));
                loginUser.setFactoryDataPermissions(SYS_DATA_PERMISSIONS_SERVICE.getFactoryDataPermissions(userId));
                TOKEN_SERVICE.setLoginUser(loginUser);
            }
        }
    }

    /**
     * 获取当前登录用户的工厂权限
     *
     * @return
     */
    public static String getLoginUserFactoryPermissionsJsonStr() {
        String factoryPermissions = "ALL";
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            factoryPermissions = JsonUtil.toJsonString(Optional.ofNullable(SecurityUtils.getLoginUser().getFactoryDataPermissions()).orElse(new HashSet<>()).stream().map(Convert::toInt).collect(Collectors.toList()));
        }
        return factoryPermissions;
    }
}
